package test.pcs;

import com.payment.lc.pcs.client.wrap.bo.*;
import com.payment.lc.pcs.client.wrap.service.ProductionWrapService;
import com.payment.lc.pcs.client.wrap.service.ProductionWrapServiceV20;
import com.payment.lc.pcs.common.enums.CyclePeriodType;
import com.payment.lc.pcs.common.enums.GroupType;
import com.payment.lc.pcs.common.enums.InstProductCategory;
import com.payment.lc.pcs.common.util.DateUtil;
import com.payment.lc.pcs.service.api.AppSettingService;
import com.payment.lc.pcs.service.api.DynamicDataService;
import com.payment.lc.pcs.service.api.ProductionService;
import com.payment.lc.pcs.service.api.fund.JMFundService;
import com.payment.lc.pcs.service.api.modify.InterestRateService;
import com.payment.lc.pcs.service.api.modify.PcsChannelService;
import com.payment.lc.pcs.service.bo.ProductionSellInfo;
import com.payment.lc.pcs.service.domain.Production;
import com.payment.lc.pcs.service.domain.SystemConfig;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import test.BaseTest;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created on 2016/8/8.
 */
public class Demo3PcsClient11Test1 extends BaseTest {


    @Autowired
    JMFundService jmFundService;


    @Autowired
    AppSettingService appSettingService;

    @Autowired
    ProductionWrapService productionWrapService;

    @Autowired
    InterestRateService interestRateService;

    @Autowired
    @Qualifier("dynamicDataService")
    DynamicDataService dynamicDataService;

    @Autowired
    @Qualifier("dynamicDataServiceLocal")
    DynamicDataService dynamicDataServiceLocal;

    @Autowired
    PcsChannelService pcsChannelService;

    @Autowired
    @Qualifier("productionService")
    ProductionService productionService;

    @Autowired
    @Qualifier("productionServiceLocal")
    ProductionService productionServiceLocal;

    @Autowired
    ProductionWrapServiceV20 productionWrapServiceV20;

    @Test
    public void test() throws Exception {
        test2();
    }

    void test1() {

        List<Production> productions = productionWrapServiceV20
                .getProductionsStatusInsensitive(GroupType.MobileFrontPageGroup, "DingqiListMore");

        display(productions.size());

        long s = System.currentTimeMillis();

        List carriers = ConcurrentUtil.getTargetList(productions, this,
                "getProductionCarrier", Production.class);
        long e = System.currentTimeMillis();

        display(carriers);
        System.out.println(e - s);

        s = System.currentTimeMillis();
        sortProductList(productions);
        e = System.currentTimeMillis();
        System.out.println(e - s);
    }

    void test2() throws Exception {

        List<Production> productions = productionWrapServiceV20
                .getProductionsStatusInsensitive(GroupType.MobileFrontPageGroup, "DingqiListMore");

        display(productions.size());

        long s = System.currentTimeMillis();

        List products = ConcurrentUtil.getTargetList(productions, this,
                "getProduct", Production.class);
        long e = System.currentTimeMillis();

        display(products);
        System.out.println(e - s);
    }

    void test6() {
        String prodCode = "JM001666";
        ProductionSellInfo sellInfo = dynamicDataService.getProductionSellInfo(prodCode);
        display(sellInfo);

        sellInfo = dynamicDataServiceLocal.getProductionSellInfo(prodCode);
        display(sellInfo);
    }

    private static class ProductionCarrier {
        private Production production;
        private boolean canPurchase;
        private BigDecimal interest;
        private Date purchaseOpenTime;
        private Date sellOutTime;

        public Production getProduction() {
            return production;
        }

        public void setProduction(Production production) {
            this.production = production;
        }

        public boolean isCanPurchase() {
            return canPurchase;
        }

        public void setCanPurchase(boolean canPurchase) {
            this.canPurchase = canPurchase;
        }

        public BigDecimal getInterest() {
            return interest;
        }

        public void setInterest(BigDecimal interest) {
            this.interest = interest;
        }

        public Date getPurchaseOpenTime() {
            return purchaseOpenTime;
        }

        public void setPurchaseOpenTime(Date purchaseOpenTime) {
            this.purchaseOpenTime = purchaseOpenTime;
        }

        public Date getSellOutTime() {
            return sellOutTime;
        }

        public void setSellOutTime(Date sellOutTime) {
            this.sellOutTime = sellOutTime;
        }
    }

    private Comparator<ProductionCarrier> productionOrderComparator = new Comparator<ProductionCarrier>() {
        @Override
        public int compare(ProductionCarrier p1, ProductionCarrier p2) {
            if (p1 == null || p2 == null) {
                return 0;
            }
            // canPurchase -> interest -> purchaseOpenTime -> purchaseCloseTime
            // can purchase p1
            if (p1.isCanPurchase()) {
                if (!p2.isCanPurchase()) {
                    return -1;
                }
                if (p1.getInterest() == null) {
                    return 1;
                }
                if (p2.getInterest() == null) {
                    return -1;
                }
                return -1 * p1.getInterest().compareTo(p2.getInterest());
            }

            // can't purchase p1
            if (p2.isCanPurchase()) {
                return 1;
            }
            // 售罄&无下期
            if (p1.getPurchaseOpenTime() == null && p2.getPurchaseOpenTime() == null) {
                if (p1.getSellOutTime() == null) {
                    return 1;
                }
                if (p2.getSellOutTime() == null) {
                    return -1;
                }
                return -1 * p1.getSellOutTime().compareTo(p2.getSellOutTime());
            }
            // 有下次开放时间
            if (p1.getPurchaseOpenTime() == null) {
                return 1;
            }
            if (p2.getPurchaseOpenTime() == null) {
                return -1;
            }
            return p1.getPurchaseOpenTime().compareTo(p2.getPurchaseOpenTime());
        }
    };

    private List<Production> sortProductList(List<Production> productions) {
        List<ProductionCarrier> carriers = new ArrayList<ProductionCarrier>();

        for (Production production : productions) {
            ProductionCarrier carrier = getProductionCarrier(production);
            if (carrier != null) {
                carriers.add(carrier);
            }
        }
        // carriers = ConcurrentUtil.getTargetList(productions, this,
        // "getProductionCarrier", Production.class);
        // 排序
        Collections.sort(carriers, productionOrderComparator);

        ArrayList<Production> ret = new ArrayList<Production>(2 * carriers.size());
        for (ProductionCarrier carrier : carriers) {
            ret.add(carrier.getProduction());
        }
        return ret;
    }

    private ProductionCarrier getProductionCarrier(Production production) {
        if (production == null) {
            return null;
        }
        // 是否在售
        ProductionCarrier carrier = new ProductionCarrier();
        carrier.setProduction(production);
        ProductionSellInfo sellInfo = productionWrapService.getProductionSellInfo(production.getProductionCode());
        if (sellInfo != null && sellInfo.getCanPurchase()) {
            ProductionValueAttributes valueAttributes = productionWrapService.getProductionValueAttributes(production);
            BigDecimal productValue = valueAttributes.getProductValue();
            carrier.setCanPurchase(true);
            carrier.setInterest(productValue);
            return carrier;
        }

        // 是否有下次开放时间
        ProductionTimeAttributes timeAttributes = productionWrapService.getProductionTimeAttributes(production);
        if (timeAttributes == null) {
            return carrier;
        }
        Date now = new Date();
        if (timeAttributes.getPurOpenTime() != null && timeAttributes.getPurOpenTime().after(now)) {
            carrier.setPurchaseOpenTime(timeAttributes.getPurOpenTime());
            return carrier;
        }
        if (timeAttributes.getNextPurOpenTime() != null && timeAttributes.getNextPurOpenTime().after(now)) {
            carrier.setPurchaseOpenTime(timeAttributes.getNextPurOpenTime());
            return carrier;
        }

        // 上期结束时间
        if (timeAttributes.getNextPurCloseTime() != null) {
            carrier.setSellOutTime(timeAttributes.getNextPurCloseTime());
        } else {
            carrier.setSellOutTime(timeAttributes.getPurCloseTime());
        }
        return carrier;
    }

    private Map<String, Object> getProduct(Production production) throws Exception {
        ProductionALLAttributes productionALLAttributes = productionWrapService.getProductionALLAttributes(production);
        if (productionALLAttributes == null)
            return null;


        ProductionAttributes productionAttributes = productionALLAttributes.getProductionAttributes();
        ProductionValueAttributes productionValueAttributes = productionALLAttributes.getProductionValueAttributes();
        Map<String, Object> productMap = new LinkedHashMap<String, Object>();
        productMap.put("prodName", productionAttributes.getProductName());
        productMap.put("valueName", productionAttributes.getProductValueName());
        BigDecimal value = productionValueAttributes.getProductValue();
        if (value != null) {
                        /*
                         * if(productionAttributes.getRaiseInterest() != null){
						 * value =
						 * value.add(productionAttributes.getRaiseInterest()); }
						 */
            if ("GD".equals(production.getMiCategory().getCode())) {
                value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
                productMap.put("value", value.toString());
            } else {
                // 添加奖励后收益率
                BigDecimal raiseInterest = productionAttributes.getRaiseInterest();
                if (raiseInterest != null
                        && InstProductCategory.Insurance.equals(productionAttributes.getProdcutInstCategory())) {
                    ProductionInsuranceAttributes productionInsuranceAttributes = productionWrapService
                            .getProductionInsuranceAttributes(production);
                    if (CyclePeriodType.YEAR.equals(productionInsuranceAttributes.getLockupPeriodUnit())
                            && (new Integer(1)).equals(productionInsuranceAttributes.getInsuranceLockupPeriod())) {
                        value = value.add(raiseInterest);

                        try {
                            String prodCode = production.getProductionCode();
                            SystemConfig sc = appSettingService.getSystemConfig("production_year_yield_tip");
                            String jsonValue = sc.getJsonValue();
                            @SuppressWarnings("unchecked")
                            Map<String, Object> yytMap = gson.fromJson(jsonValue, Map.class);
                            Object changeYearYieldTip = yytMap.get(prodCode + "-changedYearYieldTip");
                            if (changeYearYieldTip == null) {
                                changeYearYieldTip = yytMap.get(productionAttributes.getProdcutCategory().getCode()
                                        + "-changedYearYieldTip");
                            }

                            if (changeYearYieldTip != null) {
                                productMap.put("valueName", changeYearYieldTip);
                            }
                        } catch (Exception e) {
                        }

                    }
                }

                //
                productMap.put("value", value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }

            productMap.put("valueSymbol", productionValueAttributes.getProductValueSymbol());
        } else {
            productMap.put("value", "--");
        }

        productMap.put("tagList", productionAttributes.getProductTags());
        Map<String, Object> detail = new LinkedHashMap<String, Object>();
        detail.put("enable", true);
        detail.put("urlTitle", productionAttributes.getProductName());
        String url = "/app/prod?prodCode=" + production.getProductionCode();
        detail.put("url", String.format("%s" + url, ""));
        productMap.put("detail", detail);

        // 倒计时
        Map<String, Object> countDown = new LinkedHashMap<String, Object>();
        ProductionPurchaseAttributes productionPurchaseAttributes = productionWrapService
                .getProductionPurchaseAttributes(production);
        ProductionTimeAttributes timeAttributes = productionWrapService.getProductionTimeAttributes(production, true);
        long current = System.currentTimeMillis();
        Date currentTime = DateUtil.parseDate(String.valueOf(current), "yyyyMMdd");
        boolean isDisplay = false;
        if (timeAttributes != null && productionPurchaseAttributes != null) {
            // 倒计时
            Date purOpenCountDown = timeAttributes.getPurOpenCountDown();
            Date purOpenTime = timeAttributes.getPurOpenTime();
            Date purCloseCountDown = timeAttributes.getPurCloseCountDown();
            Date purCloseTime = timeAttributes.getPurCloseTime();
            String tipType = "";
            String tipContent = "";
            if (purOpenCountDown != null && purCloseCountDown != null && purOpenTime != null && purCloseTime != null) {
                tipType = "able";
                if (purOpenCountDown.compareTo(currentTime) < 0 && currentTime.compareTo(purCloseCountDown) < 0) {
                    long time = current - purOpenTime.getTime();
                    tipContent = "距开售";
                }

                if (purOpenTime.compareTo(currentTime) < 0 && purCloseTime.compareTo(currentTime) < 0) {
                    long time = current - purCloseTime.getTime();
                    tipContent = "距售罄";
                }

                if (currentTime.compareTo(purCloseTime) > 0) {
                    tipType = "disable";
                    tipContent = "售罄";
                }
            }
            countDown.put("tipContent", tipContent);
            countDown.put("tipType", tipType);
            countDown.put("isDisplay", isDisplay);
            productMap.put("countdown", countDown);

						/*
                         * Map<String, Object> tip = new LinkedHashMap<String,
						 * Object>(); String type = "enable"; String content =
						 * productionPurchaseAttributes
						 * .getHomePagePurchaseLabel();
						 * if(!productionPurchaseAttributes.isCanPurchase()) {
						 * type = "disable"; content =
						 * productionPurchaseAttributes
						 * .getHomePageNotPurchaseLabel(); }
						 * tip.put("isDiaplay", !isDisplay);
						 * tip.put("type",type); tip.put("content",content);
						 * productMap.put("tip", tip);
						 */
            ProductionSellInfo sellInfo = productionWrapService.getProductionSellInfo(production.getProductionCode());
        }
        return productMap;
    }
}
